#ifndef _MUTEX_H
#define _MUTEX_H

#include <pthread.h>

class Mutex
{
private:
    pthread_mutex_t _mutex;

public:
    Mutex()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }

    ~Mutex()
    {
        pthread_mutex_destroy(&_mutex);
    }
   
    Mutex(const Mutex&) = delete;
    Mutex& operator=(const Mutex&) = delete;

    void lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void unlock()
    {
        pthread_mutex_unlock(&_mutex); 
    }

    // condition需要传参
    pthread_mutex_t* native_handle()
    {
        return &_mutex;
    }

    // 嵌套的LockGuard类，用于自动管理锁
    class LockGuard
    {
    private:
        Mutex& _mutex;
    public:
        LockGuard(Mutex& m):_mutex(m)
        {
            _mutex.lock();
        }
        ~LockGuard()
        {
            _mutex.unlock();
        }

        LockGuard(const LockGuard&) = delete;
        LockGuard& operator=(const LockGuard&) = delete;

    };
};

#endif

